package com.aaa.stock.service.Impl;

import com.aaa.entity.*;
import com.aaa.stock.dao.InventoryDao;
import com.aaa.stock.dao.MedicinalDao;
import com.aaa.stock.dao.PurchaseDao;
import com.aaa.stock.dao.PurchaseItemDao;
import com.aaa.stock.feign.UserFeign;
import com.aaa.stock.service.PurchaseService;
import com.aaa.stock.utils.IdWorker;
import com.aaa.stock.utils.JsonUtil;
import com.aaa.stock.vo.*;
import com.aaa.utils.JWTUtils;
import com.aaa.utils.WebUtil;
import com.aaa.vo.Result;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao,Purchase> implements PurchaseService {
    @Autowired
    private PurchaseDao purchaseDao;
    @Autowired
    private InventoryDao inventoryDao;

    @Autowired
    private PurchaseItemDao purchaseItemDao;

    @Autowired
    private MedicinalDao medicinalDao;

    @Autowired
    private UserFeign userFeign;


    @Override
    public Result<IPage<Purchase>> findByAll(Integer currentPage, Integer pageSize, PurchaseVo purchaseVo) {
        IPage<Purchase> page=new Page<>(currentPage,pageSize);
        QueryWrapper<Purchase> wrapper=new QueryWrapper<>();
        if (StringUtils.hasText(purchaseVo.getProviderId())){
            wrapper.eq( "provider_id",purchaseVo.getProviderId());
        }
        if (StringUtils.hasText(purchaseVo.getApplyUserId())){
            wrapper.like("apply_user_id",purchaseVo.getApplyUserId());
        }
        if (StringUtils.hasText(purchaseVo.getStatus())){
            wrapper.eq("status",purchaseVo.getStatus());
        }

        IPage<Purchase> page1 = purchaseDao.selectPage(page, wrapper);
        return new Result<IPage<Purchase>>(200,"查询用户成功",page1);
    }

    @Override
    public Result<Boolean> GetAdd(PurchaseDtoVo purchaseVo) {
        //直接在token获取手机号
        HttpServletRequest request = WebUtil.getRequest();
        String token = request.getHeader("token");
        Map<String, Object> tokenInfo = JWTUtils.getInfo(token);
        String phone = tokenInfo.get("username").toString();
        User byUsername = userFeign.getByUsername(phone);
        IdWorker idWorker = new IdWorker();
        PurchaseDto purchaseDto = purchaseVo.getPurchaseDto();

        /**
         * 生成两张表的采购单据ID
         */
        long l = idWorker.nextId();
        //生成两位数的随机数
        int random = ((int)Math.random())*90+10;
        //保证长度和数据库长度相同
        String purchaseId = "CG"+l+random;

        /**
         * 添加采购项目详情表
         */
        List<PurchaseItemDtos> purchaseItems = purchaseVo.getPurchaseItemDtos();
        for (PurchaseItemDtos purchaseItem : purchaseItems) {
            PurchaseItem purchaseItem1 = new PurchaseItem();
            //生成雪花id
            long l1 = idWorker.nextId();
            //生成两位数的随机数
            String itemId = "" + l1+random;
            purchaseItem1.setItemId(itemId);
            purchaseItem1.setPurchaseId(purchaseId);
            purchaseItem1.setProducterId(purchaseItem.getProducterId());
            purchaseItem1.setTradeTotalAmount(purchaseDto.getPurchaseTradeTotalAmount());
            purchaseItem1.setMedicinesId(purchaseItem.getMedicinesId().toString());
            purchaseItem1.setTradePrice(purchaseItem.getTradePrice());
            purchaseItem1.setPurchaseNumber(purchaseItem.getPurchaseNumber());
            purchaseItem1.setConversion(purchaseItem.getConversion());
            purchaseItem1.setRemark(purchaseItem.getRemark());
            purchaseItem1.setMedicinesName(purchaseItem.getMedicinesName());
            purchaseItem1.setMedicinesType(purchaseItem.getMedicinesType());
            purchaseItem1.setPrescriptionType(purchaseItem.getPrescriptionType());
            purchaseItem1.setBatchNumber(purchaseItem.getBatchNumber());
            purchaseItem1.setUnit(purchaseItem.getUnit());
            purchaseItem1.setKeywords(purchaseItem.getKeywords());
            purchaseItemDao.insert(purchaseItem1);
        }

        /**
         * 添加单据表
         */

        Purchase purchase =new Purchase();
        purchase.setPurchaseId(purchaseId);
        purchase.setProviderId(purchaseDto.getProviderId());
        purchase.setPurchaseTradeTotalAmount(purchaseDto.getPurchaseTradeTotalAmount());
        purchase.setStatus("2");
        purchase.setApplyUserName(byUsername.getUserName());
        purchase.setCreateBy(byUsername.getUserName());
        purchase.setCreateTime(LocalDateTime.now());
        int insert = purchaseDao.insert(purchase);
        return new Result<Boolean>(200,"添加成功",insert>0?true:false);
    }

    //第五个页面
    @Override
    public Result<IPage<Purchase>> findByAllstatus(Integer currentPage, Integer pageSize, ExamineVo examineVo) {
        IPage<Purchase> page=new Page<>(currentPage,pageSize);
        QueryWrapper<Purchase> wrapper=new QueryWrapper<>();
        if (Objects.nonNull(examineVo.getProviderId())){
            wrapper.eq( "provider_id",examineVo.getProviderId());
        }
        if (StringUtils.hasText(examineVo.getApply_user_name())){
            wrapper.like("apply_user_id",examineVo.getApply_user_name());
        }
        wrapper.eq("status",0);
        IPage<Purchase> page1 = purchaseDao.selectPage(page, wrapper);
        return new Result<IPage<Purchase>>(200,"查询用户成功",page1);
    }

    @Override
    public Result<Boolean> Staging(PurchaseDtoVo purchaseVo) {
        //直接在token获取手机号
        HttpServletRequest request = WebUtil.getRequest();
        String token = request.getHeader("token");
        Map<String, Object> tokenInfo = JWTUtils.getInfo(token);
        String phone = tokenInfo.get("username").toString();
        User byUsername = userFeign.getByUsername(phone);
        IdWorker idWorker = new IdWorker();
        PurchaseDto purchaseDto = purchaseVo.getPurchaseDto();

        /**
         * 生成两张表的采购单据ID
         */
        long l = idWorker.nextId();
        //生成两位数的随机数
        int random = ((int)Math.random())*90+10;
        //保证长度和数据库长度相同
        String purchaseId = "CG"+l+random;

        /**
         * 添加采购项目详情表
         */
        List<PurchaseItemDtos> purchaseItems = purchaseVo.getPurchaseItemDtos();
        for (PurchaseItemDtos purchaseItem : purchaseItems) {
            PurchaseItem purchaseItem1 = new PurchaseItem();
            //生成雪花id
            long l1 = idWorker.nextId();
            //生成两位数的随机数
            String itemId = "" + l1+random;
            purchaseItem1.setItemId(itemId);
            purchaseItem1.setPurchaseId(purchaseId);
            purchaseItem1.setProducterId(purchaseDto.getProviderId());
            purchaseItem1.setTradeTotalAmount(purchaseDto.getPurchaseTradeTotalAmount());
            purchaseItem1.setMedicinesId(purchaseItem.getMedicinesId().toString());
            purchaseItem1.setTradePrice(purchaseItem.getTradePrice());
            purchaseItem1.setPurchaseNumber(purchaseItem.getPurchaseNumber());
            purchaseItem1.setConversion(purchaseItem.getConversion());
            purchaseItem1.setRemark(purchaseItem.getRemark());
            purchaseItem1.setMedicinesName(purchaseItem.getMedicinesName());
            purchaseItem1.setMedicinesType(purchaseItem.getMedicinesType());
            purchaseItem1.setPrescriptionType(purchaseItem.getPrescriptionType());
            purchaseItem1.setBatchNumber(purchaseItem.getBatchNumber());
            purchaseItem1.setUnit(purchaseItem.getUnit());
            purchaseItem1.setKeywords(purchaseItem.getKeywords());
            purchaseItemDao.insert(purchaseItem1);
        }

        /**
         * 添加单据表
         */

        Purchase purchase =new Purchase();
        purchase.setPurchaseId(purchaseId);
        purchase.setProviderId(purchaseDto.getProviderId());
        purchase.setPurchaseTradeTotalAmount(purchaseDto.getPurchaseTradeTotalAmount());
        purchase.setStatus("1");
        purchase.setApplyUserName(byUsername.getUserName());
        purchase.setCreateBy(byUsername.getUserName());
        purchase.setCreateTime(LocalDateTime.now());
        int insert = purchaseDao.insert(purchase);

        return new Result<Boolean>(200,"添加成功",insert>0?true:false);
    }

    @Override
    public Result<Boolean> tjsh(Purchase purchase) {
        if(purchase.getStatus().equals("1")){
            purchase.setStatus("2");

        }else {
            return new Result<>(200,"添加失败");
        }
        int i = purchaseDao.updateById(purchase);
        return new Result<>(200,"添加成功",i>0?true:false);
    }

    @Override
    public Result<Boolean> zf(Purchase purchase) {
        if(purchase.getStatus().equals("1")){
            purchase.setStatus("5");
        }else {
            return new Result<>(200,"添加失败");
        }
        int i = purchaseDao.updateById(purchase);
        return new Result<>(200,"添加成功",i>0?true:false);
    }


    @Override
    public Result<Boolean> rk(String purchaseId) {

        //直接在token获取手机号
        HttpServletRequest request = WebUtil.getRequest();
        String token = request.getHeader("token");
        Map<String, Object> tokenInfo = JWTUtils.getInfo(token);
        String phone = tokenInfo.get("username").toString();
        User byUsername = userFeign.getByUsername(phone);

        QueryWrapper<PurchaseItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("purchase_id", purchaseId);
        List<PurchaseItem> items = purchaseItemDao.selectList(queryWrapper);

        QueryWrapper<Purchase> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("purchase_id", purchaseId);
        Purchase purchase = purchaseDao.selectOne(queryWrapper1);

        if (purchase.getStatus().equals("3")) {;
            LocalDateTime now = LocalDateTime.now();
            for (PurchaseItem item : items) {
                IdWorker idWorker = new IdWorker();
                long l1 = idWorker.nextId();
                int random = ((int) Math.random()) * 90 + 10;
                String lla = "" + l1 + random;
                InventoryLog inventoryLog = new InventoryLog();
                inventoryLog.setInventoryLogId(lla);//入库id
                inventoryLog.setPurchaseId(item.getPurchaseId());
                inventoryLog.setMedicinesId(item.getMedicinesId());
                inventoryLog.setInventoryLogNum(item.getPurchaseNumber());
                inventoryLog.setTradePrice(item.getTradePrice());
                inventoryLog.setPrescriptionPrice(item.getTradePrice());
                inventoryLog.setTradeTotalAmount(item.getTradeTotalAmount());
                inventoryLog.setBatchNumber(item.getBatchNumber());
                inventoryLog.setMedicinesName(item.getMedicinesName());
                inventoryLog.setMedicinesType(item.getMedicinesType());
                inventoryLog.setPrescriptionType(item.getPrescriptionType());
                inventoryLog.setProducterId(item.getProducterId());
                inventoryLog.setConversion(item.getConversion());
                inventoryLog.setUnit(item.getUnit());
                inventoryLog.setProviderId(purchase.getProviderId());//供应商
                inventoryLog.setCreateTime(now);//创建时间
                inventoryLog.setCreateBy(byUsername.getUserName());//创建者
                inventoryDao.insert(inventoryLog);

                //添加进药品表中的库存量
                QueryWrapper<Medicines> queryWrapper2=new QueryWrapper<>();
                queryWrapper2.eq("medicines_id",item.getMedicinesId());
                Medicines medicines=medicinalDao.selectOne(queryWrapper2);
                Integer purchaseNumber = item.getPurchaseNumber();
                BigDecimal big=new BigDecimal(purchaseNumber.toString());
                BigDecimal bigDecimal=big.add(medicines.getMedicinesStockNum());
                medicines.setMedicinesStockNum(bigDecimal);
                medicines.setUpdateTime(LocalDateTime.now());
                medicinalDao.updateById(medicines);


            }

           /* Purchase purchase1 = new Purchase();
            purchase1.setStatus("6");
            purchase1.setApplyUserName(byUsername.getUserName());*/
            //入库操作人，入库时间
            UpdateWrapper<Purchase> wrapper = new UpdateWrapper<>();
            wrapper.eq("purchase_id", purchaseId).set("status", 6);
            wrapper.eq("purchase_id",purchaseId).set("storage_opt_user",byUsername.getUserName());
//            LocalDateTime.now()
            wrapper.eq("purchase_id", purchaseId).set("storage_opt_time", now);
            purchaseDao.update(null, wrapper);
            return new Result<>(200,"操作成功");
        }else {
            return new Result<>(400,"此状态不能修改");
        }

    }
}
